/*******************************************************************************
 * Copyright (c) 2011 Jovansonlee B. Cesar.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Jovansonlee B. Cesar - initial API and implementation
 ******************************************************************************/
package com.ivanceras.server.util;

import java.io.UnsupportedEncodingException;
import java.sql.SQLException;

import com.ivanceras.server.db.DBPool;
import com.ivanceras.shared.dao.DAO_Ad_table;
import com.ivanceras.shared.db.DAO;
import com.ivanceras.shared.db.EMF;
import com.ivanceras.shared.db.EntityManager;
import com.ivanceras.shared.db.Filter;
import com.ivanceras.shared.db.IDatabase;
import com.ivanceras.shared.db.ModelDef;
import com.ivanceras.shared.db.SchemaTable;
import com.ivanceras.shared.exception.DatabaseException;
import com.ivanceras.shared.exception.ModelDefinitionNotFoundException;
import com.ivanceras.shared.meta.ModelDefinitionProvider;
import com.ivanceras.shared.util.Configuration;

public class DataExporter {

	private static void doExport(IDatabase db, String schema, String tablePattern) throws DatabaseException{
		EntityManager em = EMF.get();
		SchemaTable[] tableList = DAOGenerator.getTableNames(db, schema, tablePattern);
		StringBuffer headxml = new StringBuffer();
		headxml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		headxml.append("\n<data>");
		writeToFile(headxml.toString());
		for(SchemaTable sctable : tableList){
			String prettyTableName = getPrettyTableName(em, sctable.getTableName());
			String capTableName = CStringUtils.capitalize(sctable.getTableName().toLowerCase());
			System.out.println("["+capTableName+"]...");
			String daotable = capTableName;
			ModelDef modeldef = null;
			try {
				modeldef =  ModelDefinitionProvider.getDefinition(daotable);
			} catch (ModelDefinitionNotFoundException e) {
				e.printStackTrace();
				throw new DatabaseException("Unable to find Metadata definition");
			}

			appendToFile("\n\t<model name=\""+sctable.getTableName()+"\" pretty=\""+prettyTableName+"\">");

			String[] attributes = modeldef.getAttributes();
			DAO[] daoList = null;
			daoList = em.getAll(new DAO(capTableName));
			for(int r = 0; r < daoList.length; r++){
				StringBuffer row = new StringBuffer();
				row.append("\n\t\t<row>");
				for(int i = 0; i < attributes.length; i++){
					String attribute = attributes[i].replace("\"", "");//trim special case side effect column which would match sql keywords 
					Object rvalue = daoList[r].get_Value(attributes[i]);
					String value = null;
					if(rvalue != null){
						try {
							value = new String(rvalue.toString().getBytes(),"UTF-8");
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
					}
					row.append("\n\t\t\t<"+attribute+"><![CDATA["+value+"]]></"+attribute+">");
				}
				row.append("\n\t\t</row>");
				appendToFile(row.toString());
			}
			appendToFile("\n\t</model>");
		}
		StringBuffer footerxml = new StringBuffer();
		footerxml.append("\n</data>");
		appendToFile(footerxml.toString());
		System.out.println("Done.");
		em.close();
	}
	private static void writeToFile(String xmlString){
		FileUtil.writeToFile(xmlString,Configuration.generatedDataDirectory, Configuration.generatedDataFile);
	}
	private static void appendToFile(String xmlString){
		FileUtil.appendToFile(xmlString,Configuration.generatedDataDirectory, Configuration.generatedDataFile);
	}
	private static String getPrettyTableName(EntityManager em, String tablename) throws DatabaseException{
		Filter[] filters = new Filter[1];
		filters[0] = new Filter("lower(tablename)", Filter.EQUAL, tablename);
		DAO_Ad_table daoTable = DAO_Ad_table.cast(em.getOne(new DAO_Ad_table(), filters));
		if(daoTable != null){
			String pretty = daoTable.getTablename();
			return pretty;
		}
		return tablename;
	}

	public static void main(String[] args) throws SQLException, DatabaseException{
		IDatabase db = DBPool.getDBPool().connectDB();
		doExport(db, Configuration.dbSchema, "ad_field");
		DBPool.getDBPool().releaseConnection(db);		
	}
}
